package com.zzb.codegenerator.generator.connect;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取连接
 * Created by zhangzhenbin on 17-4-5.
 */
public class ConnectPool {
    private static Map<String,Connection> connectionMap = new HashMap<>();

    /**
     * 获取mysql连接
     */
    public static Connection getConnection(String driverManager, String url, String userName, String password) throws Exception {
        Connection connection = null;
        if (connectionMap.containsKey(url)) {
            connection = connectionMap.get(url);
        }
        if(connection == null){
            System.out.println("正在获取数据库连接... ");
            try {
                Class.forName(driverManager).newInstance();
                connection = DriverManager.getConnection(url, userName, password);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        connectionMap.put(url,connection);
        return connection;
    }

    public static void closeAll(){
        connectionMap.values().forEach( c ->{
            try {
                c.close();
            } catch (SQLException e) {
                System.err.println("关闭连接失败");
            }
        });
    }
}
